<template>
  <div class="min-h-screen bg-gradient-to-br from-slate-900 via-gray-900 to-black flex items-center justify-center">
    <!-- 背景装饰 -->
    <div class="absolute inset-0 overflow-hidden">
      <div
        class="absolute -top-1/2 -left-1/2 w-full h-full bg-gradient-to-br from-yellow-500/10 to-orange-500/10 rounded-full blur-3xl"
      ></div>
      <div
        class="absolute -bottom-1/2 -right-1/2 w-full h-full bg-gradient-to-tl from-orange-500/10 to-amber-600/10 rounded-full blur-3xl"
      ></div>
    </div>

    <div class="relative w-full max-w-md mx-auto px-6">
      <!-- Logo区域 -->
      <div class="fixed top-8 left-8 z-10">
        <Logo />
      </div>

      <!-- 忘记密码表单 -->
      <div class="bg-white/5 backdrop-blur-lg border border-white/10 rounded-2xl p-6 shadow-2xl">
        <h2 class="text-2xl font-bold text-white text-center mb-6">重置密码</h2>

        <form @submit.prevent="handleResetPassword" class="space-y-4">
          <!-- 邮箱 -->
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-1"> 邮箱地址 </label>
            <div class="relative">
              <input
                v-model="resetForm.email"
                type="email"
                required
                placeholder="请输入注册时的邮箱地址"
                maxlength="50"
                autocomplete="off"
                class="w-full px-4 py-2.5 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-yellow-500 focus:ring-1 focus:ring-yellow-500 transition-colors"
              />
              <div class="absolute inset-y-0 right-0 pr-3 flex items-center">
                <i class="i-carbon-email text-gray-400"></i>
              </div>
            </div>
          </div>

          <!-- 验证码 -->
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-1"> 邮箱验证码 </label>
            <div class="flex space-x-3">
              <input
                v-model="resetForm.captcha"
                type="text"
                required
                placeholder="请输入验证码"
                maxlength="6"
                class="flex-1 px-4 py-2.5 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-yellow-500 focus:ring-1 focus:ring-yellow-500 transition-colors"
              />
              <CButton :loading="sendVerifyCodeLoading" :disabled="countdown > 0 || !canSendCode" @click="sendVerifyCode">
                <span v-if="countdown > 0">{{ countdown }}s</span>
                <span v-else>获取验证码</span>
              </CButton>
            </div>
          </div>

          <!-- 新密码 -->
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-1"> 新密码 </label>
            <div class="relative">
              <input
                v-model="resetForm.password"
                :type="showPassword ? 'text' : 'password'"
                required
                placeholder="请输入新密码"
                maxlength="30"
                autocomplete="new-password"
                class="w-full px-4 py-2.5 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-yellow-500 focus:ring-1 focus:ring-yellow-500 transition-colors pr-10"
              />
              <button
                type="button"
                @click="showPassword = !showPassword"
                class="bg-white/5 absolute inset-y-0 right-0 px-2 flex items-center"
              >
                <img v-if="showPassword" src="/assets/image/open-eyes.svg" class="w-4 h-4" />
                <img v-else src="/assets/image/close-eyes.svg" class="w-4 h-4" />
              </button>
            </div>
            <!-- 密码强度指示 -->
            <div v-if="resetForm.password" class="mt-1 flex items-center space-x-2">
              <div class="flex space-x-1">
                <div
                  v-for="i in 4"
                  :key="i"
                  class="h-1 w-4 rounded-full transition-colors"
                  :class="passwordStrength >= i ? getStrengthColor(passwordStrength) : 'bg-gray-500'"
                ></div>
              </div>
              <div class="text-xs" :class="getStrengthTextColor(passwordStrength)">
                {{ getStrengthText(passwordStrength) }}
              </div>
            </div>
          </div>

          <!-- 确认新密码 -->
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-1"> 确认新密码 </label>
            <div class="relative">
              <input
                v-model="resetForm.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'"
                required
                placeholder="请再次输入新密码"
                maxlength="30"
                autocomplete="new-password"
                class="w-full px-4 py-2.5 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-yellow-500 focus:ring-1 focus:ring-yellow-500 transition-colors pr-10"
              />
              <button
                type="button"
                @click="showConfirmPassword = !showConfirmPassword"
                class="bg-white/5 absolute inset-y-0 right-0 px-2 flex items-center"
              >
                <img v-if="showConfirmPassword" src="/assets/image/open-eyes.svg" class="w-4 h-4" />
                <img v-else src="/assets/image/close-eyes.svg" class="w-4 h-4" />
              </button>
            </div>
            <div v-if="resetForm.confirmPassword && resetForm.password !== resetForm.confirmPassword" class="text-red-400 text-xs mt-1">
              密码不一致
            </div>
          </div>

          <!-- 重置密码按钮 -->
          <button
            type="submit"
            :disabled="isLoading || !isFormValid"
            class="w-full py-2.5 px-4 text-white font-semibold rounded-lg transition-all duration-300 transform cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none"
            :class="[
              isFormValid && !isLoading
                ? 'bg-gradient-to-r from-yellow-500 to-orange-500 hover:from-yellow-600 hover:to-orange-600'
                : 'bg-gray-500',
            ]"
          >
            <span v-if="isLoading" class="flex items-center justify-center">
              <div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></div>
              重置中...
            </span>
            <span v-else>重置密码</span>
          </button>
        </form>

        <!-- 返回登录链接 -->
        <div class="mt-6 text-center">
          <span class="text-gray-400 text-sm">记起密码了？</span>
          <NuxtLink to="/login" class="text-yellow-400 hover:text-yellow-300 font-medium ml-1 transition-colors text-sm">
            返回登录
          </NuxtLink>
        </div>
      </div>

      <!-- 底部信息 -->
      <div class="mt-6 text-center text-xs text-gray-500">
        <p>
          重置密码即表示同意我们的
          <a href="/user-agreement" class="text-yellow-400 hover:text-yellow-300">用户协议</a>
          和
          <a href="/privacy-policy" class="text-yellow-400 hover:text-yellow-300">隐私政策</a>
        </p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { ref, reactive, computed } from 'vue';
import { querySendForgetPasswordCode, queryResetPassword } from '~/apis/auth';

// SEO配置
useSEO({
  title: '忘记密码 - 球球助手',
  description: '重置球球助手账户密码，安全便捷的密码找回服务',
  keywords: '忘记密码,重置密码,密码找回,球球助手',
});

// 页面元信息
definePageMeta({ layout: 'auth' });

// 响应式数据
const showPassword = ref(false);
const showConfirmPassword = ref(false);
const isLoading = ref(false);
const countdown = ref(0);
const sendVerifyCodeLoading = ref(false);

// const resetForm = reactive({
//   email: '15360001247@163.com',
//   captcha: '',
//   password: 'admin123456',
//   confirmPassword: 'admin123456',
// });
const resetForm = reactive({
  email: '',
  captcha: '',
  password: '',
  confirmPassword: '',
});

// 密码强度计算
const passwordStrength = computed(() => {
  const password = resetForm.password;
  if (!password) return 0;

  let strength = 0;
  if (password.length >= 6) strength++;
  if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
  if (/\d/.test(password)) strength++;
  if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength++;

  return strength;
});

// 发送验证码按钮是否可用
const canSendCode = computed(() => {
  return resetForm.email && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(resetForm.email);
});

// 表单验证
const isFormValid = computed(() => {
  return (
    resetForm.email &&
    resetForm.captcha &&
    resetForm.password &&
    resetForm.confirmPassword &&
    resetForm.password === resetForm.confirmPassword
  );
});

// 密码强度相关方法
const getStrengthColor = (strength: number) => {
  switch (strength) {
    case 1:
      return 'bg-red-500';
    case 2:
      return 'bg-yellow-500';
    case 3:
      return 'bg-yellow-500';
    case 4:
      return 'bg-green-500';
    default:
      return 'bg-gray-500';
  }
};

const getStrengthTextColor = (strength: number) => {
  switch (strength) {
    case 1:
      return 'text-red-400';
    case 2:
      return 'text-yellow-400';
    case 3:
      return 'text-yellow-400';
    case 4:
      return 'text-green-400';
    default:
      return 'text-gray-400';
  }
};

const getStrengthText = (strength: number) => {
  switch (strength) {
    case 1:
      return '密码强度：弱';
    case 2:
      return '密码强度：一般';
    case 3:
      return '密码强度：良好';
    case 4:
      return '密码强度：很强';
    default:
      return '请输入密码';
  }
};

// 发送验证码
const sendVerifyCode = async () => {
  sendVerifyCodeLoading.value = true;
  try {
    await querySendForgetPasswordCode({ email: resetForm.email });
    // 开始倒计时
    countdown.value = 120;
    const timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) clearInterval(timer);
    }, 1000);
    ElMessage.success('验证码发送成功，请注意查收');
  } finally {
    sendVerifyCodeLoading.value = false;
  }
};

// 重置密码
const handleResetPassword = async () => {
  if (!isFormValid.value) return;

  isLoading.value = true;
  try {
    await queryResetPassword({
      email: resetForm.email,
      captcha: resetForm.captcha,
      password: resetForm.password,
    });
    ElMessage.success('密码重置成功，请使用新密码登录');
    navigateTo('/login');
  } finally {
    isLoading.value = false;
  }
};

// 防止已登录用户访问
onMounted(() => {
  const userStore = useUserStore();
  if (userStore.isLoggedIn) navigateTo('/');
});
</script>

<style scoped>
/* 页面样式 */
</style>
